package cn.ciis.basic.event;

import cn.ciis.basic.plugin.CiisSessionContext;
import com.jfinal.kit.LogKit;
import com.jfinal.kit.PropKit;
import net.dreamlu.event.core.EventListener;
import org.tio.core.ChannelContext;
import org.tio.core.Tio;
import org.tio.core.stat.ChannelStat;
import org.tio.monitor.RateLimiterWrap;

public class RateLimiterEventListen {

    /**
     * 流控处理
     * @param event
     */
    @EventListener(async = true)
    public void listenCheckIpEvent(RateLimiterEvent event){

        ChannelContext channelContext = event.getChannelContext();

        CiisSessionContext ciisSessionContext = (CiisSessionContext) channelContext.get("ciisSessionContext");

        ChannelStat channelStat = channelContext.stat;
        LogKit.info("进入流量控制了！{}",channelStat.receivedPackets.get());
        if (channelStat.receivedTcps.get() > PropKit.getInt("skip.warn.count")) { //前面几条命令不计入令牌桶
            RateLimiterWrap rateLimiterWrap = ciisSessionContext.getRequestRateLimiter();
            boolean[] ss = rateLimiterWrap.tryAcquire();

            if (ss[0] == false && ss[1] == false) {
                LogKit.error("{} 数据上传速度已达到最大阈值， 将拉黑其IP", channelContext.toString());
                Tio.IpBlacklist.add(channelContext.getClientNode().getIp());

            } else if (ss[0] == false && ss[1] == true) {
                int warnCount = rateLimiterWrap.getWarnCount().get();
                LogKit.error("{} 数据上传速度过快。，已经发生{}次", channelContext.toString(),warnCount);

            }
        }

    }

}
